package My

import (
	"errors"
	"fmt"
	"db2s/ETL"
	"db2s/global"
	"strings"
)

type TableRows struct{}

func (my TableRows) Sql(s global.StartPart) (selectSql string, err error) {
	var (
		event = "[mysqlSql]"
		res   colAndWhereResult
		w     = []string{" "}
	)
	if len(s.TableInfo.Schema) == 0 || len(s.TableInfo.BackendTableName) == 0 {
		err = errors.New(fmt.Sprintf("%v query sql general fail. schema or table is entry. Execution process:{schema:%v,table:%v}", event, s.TableInfo.Schema, s.TableInfo.BackendTableName))
		return "", err
	}
	if res, err = colAndWhere(s); err != nil {
		//err = errors.New(fmt.Sprintf("%v %v", Event, err))
		return
	}
	selectSql = fmt.Sprintf("select %v %v \n"+
		"from %v T\n"+
		"where 1 = 1 %v \n"+
		"%v",
		hitSpecify(s), strings.Join(res.selectColumn, ","),
		tableObject(s.TableInfo.Schema, s.TableInfo.BackendTableName, s.TableInfo.PartitionName),
		strings.Join(append(w, res.whereCondition...), " and "),
		res.orderByColumn)
	return selectSql, nil
}

/*
Data MySQL 通过where条件查询表的分段数据（查询数据生成带有greatDBbCheck标识的数据块）
*/
func (my TableRows) Data(s global.RowsDataInput) (result global.ExecSqlResult, err error) {
	var (
		event = "[mysqlData]"
	)
	result.ExecSql = s.Sql
	if result.Timeout, result.Result, err = ExecSelectSql(ExecSqlInputS{
		Ss:           s,
		Event:        event,
		SelectSqlStr: s.Sql,
		Expect:       ETL.GarthStringPointGarth,
	}); err != nil {
		err = errors.New(fmt.Sprintf("%v %v", event, err))
		return
	}
	return
}

/*
MissData 查询无索引表的数据（使用limit分页的方式），并排序
*/
func (my TableRows) MissData(s global.RowsDataInput) (result global.ExecSqlResult, err error) {
	var (
		event = "[MySQLMissData]"
		res   colAndWhereResult
	)
	s.SelectColumn.OutputColumnType = "all"
	if res, err = colAndWhere(global.StartPart{
		SelectColumn: s.SelectColumn,
	}); err != nil {
		return
	}
	result.ExecSql = fmt.Sprintf("select %v \n"+
		"from %v "+
		"where 1= 1 %v \n",
		strings.Join(res.selectColumn, ","),
		tableObject(s.TableInfo.Schema, s.TableInfo.BackendTableName, s.TableInfo.PartitionName),
		rowsLimitC(s.TableInfo.RowsLimit))
	if result.Timeout, result.Result, err = ExecSelectSql(ExecSqlInputS{
		Ss:           s,
		Event:        event,
		SelectSqlStr: result.ExecSql,
		Expect:       ETL.FlowAny,
	}); err != nil {
		return
	}
	return
}
